import requests

class HttpDown:
    method = 'GET'
    def __init__(self,url):
        self.verify = False
        self.url = url
        self.headers = None
        self.cookies = None
        self.data = None
        self.method = 'GET'
        self.save_path = None
        self.timeout = 10

    def set_headers(self, headers):
        self.headers = headers
        return self

    def set_data(self, data):
        self.data = data
        return self

    def set_cookies(self, cookies):
        self.cookies = cookies
        return self

    def set_save_path(self, save_path):
        self.save_path = save_path
        return self

    def set_timeout(self, timeout):
        self.timeout = timeout
        return self

    def set_verify(self,b_verify: bool = True):
        self.verify = b_verify
        return self

    def get_requests(self):
        """
            HTTP 下载器

            参数：
            - url: 请求的URL
            - method: HTTP方法（GET/POST/PUT等），默认为GET
            - headers: 请求头（字典格式）
            - data: 请求体数据（字典或字符串）
            - cookies: Cookie（字典格式）
            - save_path: 文件保存路径（不提供则返回内容）
            - timeout: 超时时间（秒）

            返回：
            - 如果 save_path 为 None，返回响应内容(bytes)，否则返回 None
            """
        try:
            # 发送请求
            response = requests.request(
                method=self.method.upper(),
                url=self.url,
                headers=self.headers,
                data=self.data,
                cookies=self.cookies,
                timeout=self.timeout,
                verify=self.verify,
                stream=self.save_path is not None  # 启用流式下载用于大文件
            )
            response.raise_for_status()  # 检查HTTP错误状态码

            # 处理结果
            if self.save_path:
                # 流式写入文件
                with open(self.save_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:
                            f.write(chunk)
                # print(f"文件已保存至：{save_path}")
                return True
            else:
                return response.content

        except requests.exceptions.RequestException as e:
            print(f"请求发生错误：{str(e)}")
            return False
